package com.yoyo.wauth.test;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@Service
public class RegionService {

    private Map<String, Map<String, String>> regionCache = new ConcurrentHashMap<>();

    public void loadRegionFromExcel(MultipartFile file) throws IOException {
        // 读取Excel文件
        Workbook workbook = new XSSFWorkbook(file.getInputStream());
        Sheet sheet = workbook.getSheetAt(0);

        Map<String, Map<String, String>> newRegionData = new HashMap<>();

        // 获取支持的语言列表（从表头）
        List<String> languages = new ArrayList<>();
        Row headerRow = sheet.getRow(0);
        for (int i = 1; i < headerRow.getLastCellNum() - 1; i++) {
            languages.add(headerRow.getCell(i).getStringCellValue());
        }

        // 读取数据
        for (int i = 1; i <= sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i);
            String regionCode = row.getCell(0).getStringCellValue();
            int status = (int) row.getCell(row.getLastCellNum() - 1).getNumericCellValue();

            if (status == 1) {  // 只加载启用的地区
                Map<String, String> translations = new HashMap<>();
                for (int j = 0; j < languages.size(); j++) {
                    String lang = languages.get(j);
                    String name = row.getCell(j + 1).getStringCellValue();
                    translations.put(lang, name);
                }
                newRegionData.put(regionCode, translations);
            }
        }

        // 更新缓存
        regionCache = newRegionData;
    }

    public String getRegionName(String regionCode, String language) {
        Map<String, String> translations = regionCache.get(regionCode);
        if (translations == null) {
            return regionCode;  // 如果找不到翻译，返回地区编码
        }
        return translations.getOrDefault(language, translations.get("en_US"));  // 默认返回英文
    }

    public List<RegionVO> getAllRegions(String language) {
        return regionCache.entrySet().stream()
                .map(entry -> new RegionVO(entry.getKey(),
                        entry.getValue().getOrDefault(language, entry.getValue().get("en_US"))))
                .collect(Collectors.toList());
    }
}
